package com.jichangxiu.flow.server.action;

import com.jichangxiu.flow.server.core.entity.Bo.ElBo;
import com.jichangxiu.flow.server.core.entity.dto.LogicFlow;
import com.jichangxiu.flow.server.core.parser.impl.LiteFlowParser;
import com.yomahub.liteflow.builder.el.LiteFlowChainELBuilder;
import com.yomahub.liteflow.core.FlowExecutor;
import com.yomahub.liteflow.flow.LiteflowResponse;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * LiteFlowAction:
 *
 * @author Hz
 * @create 2025-05-04 13:18
 */
@RestController
@RequestMapping("/lite/flow")
public class LiteFlowAction {

    @Resource
    private FlowExecutor flowExecutor;

    @PostMapping("/getEl")
    public String getEl(@RequestBody LogicFlow logicFlow) {
        String message = "";
        try {
            LiteFlowParser liteFlowParser = new LiteFlowParser(logicFlow);
            ElBo elBo = liteFlowParser.extractElBo();
            System.out.println(elBo.toElString());
            message = elBo.toElString();
        } catch (Exception ex) {
            ex.printStackTrace();
            message = ex.getMessage();
        }
        return message;
    }

    @PostMapping("/run")
    public String run(@RequestBody LogicFlow logicFlow) {
        String message = "";
        String el = "";
        try {
            LiteFlowParser liteFlowParser = new LiteFlowParser(logicFlow);
             el = liteFlowParser.extractElBo().toElString();
            System.out.println(el);
            LiteFlowChainELBuilder.createChain().setChainName("chain").setEL(el).build();
            LiteflowResponse response = flowExecutor.execute2Resp("chain");
            message = response.isSuccess() ? "执行成功" : response.getCause().getMessage();
        } catch (Exception ex) {
            ex.printStackTrace();
            message = ex.getMessage();
        }
        return message;
    }

}
